require 'json'
require 'open-uri'
require 'digest/sha1'

module Whurls
  MAJOR_VERSION = 0
  MINOR_VERSION = 0
  TINY_VERSION  = 1
  VERSION       = [MAJOR_VERSION, MINOR_VERSION, TINY_VERSION].join('.')

  # REST_URL      = 'http://www.whurls.com/'.freeze
  REST_URL      = 'http://127.0.0.1:3000/'.freeze

  class API
    attr_accessor :token

    def initialize(token)
      @token = token
    end

    def params
      {:token => self.token, :signature => self.signature, :format => 'xml'}
    end

    def signature
      Digest::SHA1.hexdigest(self.token + API.api_key + API.secret_key)
    end

    def test
      url = [
        "#{File.join(REST_URL, 'connections')}.json",
        build_query_string(:token => token, :signature => signature)
      ].join('?')

      JSON.parse(open(url, 'User-Agent' => "Whurls/#{VERSION}").read)
    end

    class << self
      attr_accessor :api_key
      attr_accessor :secret_key
    end

  private
    def call(request, params = {})
    
    end

    def build_query_string(params = {})
      params.collect{|k,v| "#{k.to_s}=#{CGI::escape v.to_s}"}.join('&')
    end
  end
end